﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using cognysClient.CognyService;


namespace cognysClient.Admin
{
    public partial class WebForm5 : System.Web.UI.Page
    {
       
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        //session variables used for displaying the qor and pric div when selectedindexchanged is fired from pric and qor list.
        protected void Page_LoadComplete(object sender, EventArgs e)
        {
            if (Session["pric"] == null)
            {
                Session["pric"] = "false";
            }
            if (IsPostBack)
            {
                if (Session["pric"].ToString() == "false")
                {
                    divPricResult.Style.Add("display", "none");

                }
                if (Session["pric"].ToString() == "true")
                {
                     divPricResult.Style.Add("display", "block");
                     Session["pric"] = "false";
                }
            }
            if (Session["qor"] == null)
            {
                Session["qor"] = "false";
            }
            if (IsPostBack)
            {
                if (Session["qor"].ToString() == "false")
                {
                    divQorResult.Style.Add("display", "none");

                }
                if (Session["qor"].ToString() == "true")
                {
                    divQorResult.Style.Add("display", "block");
                    Session["qor"] = "false";
                }      
            }
        }

        //gets the average score from memory results.
        public string getMemoryAvg()
        {
            try
            {
                var client = new Service1Client();
                string avg = client.getMemoryAvg();
                if (avg.Length > 4)
                {
                    avg = avg.Substring(0, 4);
                }
                return avg;
            }
            catch
            {
                return "0";
            }
        }

        //gets the stroop baseline value from the person selected in the listbox.
        public string getStroopBaseLine()
        {
            try
            {
                var client = new Service1Client();
                Baseline bl = new Baseline();
                bl = client.getBaseline(Guid.Parse(lbName.SelectedValue));
                string baseline = bl.ScoreStroop.ToString();
                if (baseline != "")
                {
                    return baseline;
                }
                else
                {
                    return "Ej registrerat";
                }
            }
            catch
            {
                return "Ej registrerat";
            }
        }

        //gets the memory baseline value from the person selected in the listbox.
        public string getMemoryBaseLine()
        {
            try
            {
                var client = new Service1Client();
                Baseline bl = new Baseline();
                bl = client.getBaseline(Guid.Parse(lbName.SelectedValue));
                string baseline = bl.ScoreMemory.ToString();
                if (baseline != "")
                {
                    return baseline;
                }
                else
                {
                    return "Ej registrerat";
                }
            }
            catch
            {
                return "Ej registrerat";
            }
        }

        //gets the tmt baseline value from the person selected in the listbox.
        public string getTMTBaseLine()
        {
            try
            {
                var client = new Service1Client();
                Baseline bl = new Baseline();
                bl = client.getBaseline(Guid.Parse(lbName.SelectedValue));
                string baseline = bl.ScoreTMT.ToString();
                if (baseline != "")
                {
                    return baseline;
                }
                else
                {
                    return "Ej registrerat";
                }
            }
            catch
            {
                return "Ej registrerat";
            }
        }

        //gets the average score from stroop results.
        public string getStroopAvg()
        {
            try
            {
                var client = new Service1Client();
                string avg = client.getStroopAvg();
                if (avg.Length > 5)
                {
                    avg = avg.Substring(0, 5);
                }
                return avg; 
            }
            
            catch
            {
                return "0";
            }

        }

        //gets the average score from TMT results.
        public string getTMTAvg()
        {
            try
            {
                var client = new Service1Client();
                string avg = client.getTMTAvg();
                if (avg.Length > 4)
                {
                    avg = avg.Substring(0, 4);
                }
                return avg;
            }
            catch
            {
                return "0";
            }

        }

        //gets the highest value result from memory.
        public string getMemoryTop()
        {
            try
            {
                var client = new Service1Client();
                string top = client.getMemoryTop();
                return top; 
            }
            catch
            {
                return "0";
            }
        }

        //gets the highest value result from TMT.
        public string getTMTTop()
        {
            try
            {
                var client = new Service1Client();
                string top = client.getTMTTop();
                return top;  
            }
            catch
            {
                return "0";
            }
        }

        //gets the highest value result from Stroop.
        public string getStroopTop()
        {
            try
            {
                var client = new Service1Client();
                string top = client.getStroopTop();
                return top; 
            }
            catch
            {
                return "0";
            }
        }

        //search function 
        public void txtChanged(object sender, EventArgs e)
        {
            //Get text from textbox
            string text = ((TextBox)sender).Text;

            var client = new CognyService.Service1Client();
            var persons = (from p in client.getPersons(text)
                           select new
                           {
                               ID = p.ID,
                               fullname = p.Firstname + " " + p.Lastname
                           }).ToList();

            lbName.DataSource = persons;
            lbName.DataTextField = "fullname";
            lbName.DataValueField = "ID";
            lbName.DataBind();

        }

        //a method which is called when a persons name is clicked on in the listbox, gets various results.
        public void selectedPerson(object sender, EventArgs e)
        {
            var client = new CognyService.Service1Client();
            var resultMemory = client.getMemoryResult(Guid.Parse(lbName.SelectedValue));
            var resultStroop = client.getStroopResult(Guid.Parse(lbName.SelectedValue));
            var resultTMT = client.getTMTResult(Guid.Parse(lbName.SelectedValue));

            //fills the gridMemory with results for the selected person.
            GridMemory.DataSource = resultMemory;
            GridMemory.DataBind();

            //fills the gridStroop with results for the selected person.
            GridStroop.DataSource = resultStroop;
            GridStroop.DataBind();

            //fills the gridTmt with results for the selected person.
            GridTMT.DataSource = resultTMT;
            GridTMT.DataBind();

            //fills the dropdownlist with QoR results.
            setRegisteredQoRDates();

            //fills the dropdownlist with PRiC results.
            setRegisteredPRiCDates();

            //displays the 2nd menu, and hide qor and pric divs if they are visible.
            divResult.Style.Add("display", "block");
            divQorGrid.Style.Add("display", "none");
            divPric.Style.Add("display", "none");
        }

        //fills the dropdownlist in the qor div with registered QoR results for that person.
        public void setRegisteredQoRDates()
        {
            var client = new Service1Client();
            var list = client.getQorRegDates(Guid.Parse(lbName.SelectedValue));


            ddlDatePickerQoR.Items.Clear();
            ddlDatePickerQoR.Items.Add(new ListItem("Välj datum", null));
            ddlDatePickerQoR.DataSource = list;
            ddlDatePickerQoR.DataTextField = "regDate";
            ddlDatePickerQoR.DataValueField = "regDate";
            ddlDatePickerQoR.DataBind();
        }

        //fills the dropdownlist in the Pric div with registered Pric results for that person.
        public void setRegisteredPRiCDates()
        {
            var client = new Service1Client();
            var list = client.getPricRegDates(Guid.Parse(lbName.SelectedValue));

            ddlDatePickerPRiC.Items.Clear();
            ddlDatePickerPRiC.Items.Add(new ListItem("Välj datum", null));
            ddlDatePickerPRiC.DataSource = list;
            ddlDatePickerPRiC.DataTextField = "regDate";
            ddlDatePickerPRiC.DataValueField = "regDate";
            ddlDatePickerPRiC.DataBind();
        }

        //method called when a qor result is selected from the dropdownlist.
        protected void ddlDatePickerQoR_SelectedIndexChanged(object sender, EventArgs e)
        {
            var value = ddlDatePickerQoR.SelectedItem.Value;
                try
                {
                    //calls the method to display the qor result.
                    getQorResultByDate(value, Guid.Parse(lbName.SelectedValue));
                }
                catch
                {
                    
                }
            
            //session variable to display divs.
            Session["qor"] = "true";
            divQorGrid.Style.Add("display", "block");
        }
        //method called when a Pric result is selected from the dropdownlist.
        protected void ddlDatePickerPRiC_SelectedIndexChanged(object sender, EventArgs e)
        {
            var value = ddlDatePickerPRiC.SelectedItem.Value;
                try
                {
                    //calls the method to display the Pric result.
                    getPricResultByDate(value, Guid.Parse(lbName.SelectedValue));
                }
                catch
                {

                }
            //session variable to display divs.
            Session["pric"] = "true";
            divPric.Style.Add("display", "block");
        }

        //displays the QoR result.
        public void getQorResultByDate(string selectedValue, Guid person)
        {
            var client = new Service1Client();
            var resultQorList = client.getUserSingleResultQoR(selectedValue, person);
            
            var qorslist = client.getQorQuestions().ToList();

            //joins resultQor with Qor object to get question and answer in same.
            var resylts = resultQorList
                                        .Join(qorslist,
                                              c => c.Question,
                                              o => o.ID,
                                              (c, o) => new
                                              {
                                                  o.Question,
                                                  c.Answer
                                              }).ToList();

            List<KeyValuePair<string, int>> kv = new List<KeyValuePair<string, int>>();

            decimal average;
            var total = 0;

            foreach (var resylt in resylts)
            {
                var item = new KeyValuePair<string, int>(resylt.Question, resylt.Answer);
                kv.Add(item);
                total += resylt.Answer;
            }
            average = Decimal.Parse(total.ToString()) / Decimal.Parse(kv.Count().ToString());

            //sets the average and total to labels.
            lblTotal.Text = total.ToString();
            lblAverage.Text = Math.Round(average, 2).ToString();

            //binds the list to a gridview
            gridQor.DataSource = kv;
            gridQor.DataBind();
        }
        //Displays the selected Pric result.
        public void getPricResultByDate(string selectedValue, Guid person)
        {
            var client = new CognyService.Service1Client();
            var resultPricList = client.getUserSingleResultPric(selectedValue, person);

            var pricList = client.getPricQuestions().ToList();

            //joins resultPric with Pric object to get question and answer in same.
            var resylts = resultPricList
                                        .Join(pricList,
                                              c => c.Question,
                                              o => o.ID,
                                              (c, o) => new
                                              {
                                                  o.Question,
                                                  c.Answer
                                              }).ToList();

            List<KeyValuePair<string, string>> kv = new List<KeyValuePair<string, string>>();

            decimal average;
            var total = 0;
            decimal totalDivider = 0;

            //adds question and answer to the keyvaluepair-list.
            //Calculates the total and average score.
            foreach (var resylt in resylts)
            {
                var item = new KeyValuePair<string, string>(resylt.Question, resylt.Answer);
                kv.Add(item);

                try
                {
                    total += int.Parse(resylt.Answer);
                    totalDivider++;
                }
                catch
                {

                }
            }
            average = Decimal.Parse(total.ToString())/totalDivider;

            //sets the average and total to labels.
            lblTotalPric.Text = total.ToString();
            lblAveragePric.Text = Math.Round(average, 2).ToString();

            //binds the list to a gridview
            GridPric.DataSource = kv;
            GridPric.DataBind();
        }
    }
}